package fafmessenger.boundary;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import fafmessenger.control.InboxController;
import fafmessenger.entity.Contact;
import fafmessenger.entity.Message;
import fafmessenger.entity.Response;

public class ConversationGUI extends ListActivity {
	private ArrayList<Message> messagesBeingShowed;
	private InboxController inboxController;
	private Contact currentContact;
	private String mobilenumber;
	private String nickname;
	public ProgressDialog progressDialog;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.conversation);
        
        mobilenumber = getIntent().getExtras().get("mobilenumber").toString();
        nickname = getIntent().getExtras().get("nickname").toString();
        
        inboxController = new InboxController(this);
        
        currentContact = inboxController.getContactByMobilenumber(mobilenumber);
        
        messagesBeingShowed = currentContact.getMessages();
        setListAdapter(new OrderAdapter(this, R.layout.row_message, messagesBeingShowed));

        ListView messageList = getListView();
        messageList.setTextFilterEnabled(true);
        messageList.setSelection(messagesBeingShowed.size()-1);
     
        
        final Button buttonSend = (Button) findViewById(R.id.send_message);
        buttonSend.setOnClickListener(new View.OnClickListener() {		
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EditText editText = (EditText)findViewById(R.id.input_message);
				String body = editText.getText().toString();
				
				SendMessageThread thread = new SendMessageThread(body);
				setProgressDialog("Please wait...", "Sending message");
	        	progressDialog.show();	        	
	        	thread.start();
			}
		});
    }
    
   @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.conversationmenu, menu);
		return true;
	}
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            
        case R.id.delete_conversation:  
        	mobilenumber = getIntent().getExtras().get("mobilenumber").toString();
        	inboxController.deleteConversation(mobilenumber);
        	Toast toast = Toast.makeText(this, "Conversation has been deleted.", 10);
        	toast.show();
        	finish();
        	return true;
        	
        case R.id.refresh_conversation:
        	RefreshThread refreshthread = new RefreshThread();
        	
        	setProgressDialog("Please wait...", "Refreshing");        	
        	refreshthread.start();
        	return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    public void setProgressDialog(String title, String message) {
    	progressDialog = ProgressDialog.show(this, title, message, true, false);
    }
    
    private class RefreshThread extends Thread {
    	@Override
    	public void run() {
    		boolean result = inboxController.refresh();
        	
        	if (result) {
        		ArrayList<Contact> contactsBeingShowed = inboxController.getAllContactsWithMessages();
            	currentContact = inboxController.getContactByMobilenumber(mobilenumber);                
                messagesBeingShowed = currentContact.getMessages();
        	}
        	
        	handler.sendEmptyMessage(0);
    	}
    	
    	private Handler handler = new Handler() {
            @Override
            public void handleMessage(android.os.Message msg) {
            	progressDialog.dismiss();
            	setListAdapter(new OrderAdapter(ConversationGUI.this, R.layout.row_message, messagesBeingShowed));            
                ListView messageList = getListView();
                messageList.setTextFilterEnabled(true);
                messageList.setSelection(messagesBeingShowed.size()-1);
            }
            };
    }
    
    private class SendMessageThread extends Thread {
    	
    	private String body;
    	private Response r;
    	
    	public SendMessageThread(String body) {
    		this.body = body;
    	}
    	
    	@Override
    	public void run() {
    		r = inboxController.sendMessage(mobilenumber, body);      	
        	handler.sendEmptyMessage(0);
    	}
    	
    	private Handler handler = new Handler() {
            @Override
            public void handleMessage(android.os.Message msg) {
            	progressDialog.dismiss();
            	
            	if (r == null){
            		Toast toast = Toast.makeText(ConversationGUI.this, "Unable to connect to server", 10);
        			toast.show();
            	}
            	
            	else {
            		Toast toast = Toast.makeText(ConversationGUI.this, r.getDescription(), 10);
            		toast.show();
                	EditText editText = (EditText)findViewById(R.id.input_message);
    				editText.setText("");
            	}
            	
            }
    	};
    }
    
    private class OrderAdapter extends ArrayAdapter<Message> {

        private ArrayList<Message> messagesOfContact;

        public OrderAdapter(Context context, int textViewResourceId, ArrayList<Message> messagesOfContact) {
                super(context, textViewResourceId, messagesOfContact);
                this.messagesOfContact = messagesOfContact;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.row_message, null);
                }
                
                Message m = messagesOfContact.get(position);
                if (m != null) {
                        TextView mt = (TextView) v.findViewById(R.id.messagebody);
                        if (mt != null) {                           
                        	mt.setText(m.getBody());
                        }
                        
                        TextView tt = (TextView) v.findViewById(R.id.messagetime);
                        if (tt != null){
                        	Integer minutes = m.getTimestamp().getMinutes();
                        	String newMinutes = minutes.toString();
                        	if (minutes < 10){
                        		newMinutes = "0"+minutes;
                        	}    	
                        	tt.setText(m.getTimestamp().getHours()+":"+newMinutes);
                        	}
                        }
                return v;
        }
    }
}
